package com.asset.dispoal.plaintiffConfiguration.service.commom;

import com.asset.dispoal.plaintiffConfiguration.domain.db.entity.SysPlaintiffConfiguration;
import com.asset.dispoal.plaintiffConfiguration.domain.db.mapper.SysPlaintiffConfigurationMapper;
import com.asset.dispoal.plaintiffConfiguration.dto.PlaintiffFileRequest;
import com.asset.dispoal.plaintiffConfiguration.dto.SysPlaintiffConfigurationRequest;
import com.asset.dispoal.plaintiffConfiguration.service.converter.PlaintiffConfigurationConverter;
import com.asset.dispoal.plaintiffFile.domain.db.entity.PlaintiffFile;
import com.asset.dispoal.plaintiffFile.domain.db.mapper.PlaintiffFileMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tech.mhuang.pacebox.core.ddd.BaseCommand;
import tech.mhuang.pacebox.core.exception.BusinessException;
import tech.mhuang.pacebox.core.id.BaseIdeable;
import tech.mhuang.pacebox.core.io.IOUtil;
import tech.mhuang.pacebox.core.util.CollectionUtil;
import tech.mhuang.pacebox.springboot.protocol.Result;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.List;


/**
 * @author qr
 * @date 2022/3/21$
 */
@Component
public class PlaintiffConfigurationInsertCommand implements BaseCommand<SysPlaintiffConfigurationRequest, Result> {
    @Autowired
    private Environment environment;
    @Autowired
    SysPlaintiffConfigurationMapper sysPlaintiffConfigurationMapper;
    @Autowired
    PlaintiffFileMapper plaintiffFileMapper;

    @Autowired
    BaseIdeable<String> snowFlake;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Result execute(SysPlaintiffConfigurationRequest sysPlaintiffConfigurationRequest) {
        String generateId = snowFlake.generateId();
        sysPlaintiffConfigurationRequest.setId(generateId);
        SysPlaintiffConfiguration sysPlaintiffConfiguration = PlaintiffConfigurationConverter.INSTANCE.reqToDo(sysPlaintiffConfigurationRequest);
        sysPlaintiffConfigurationMapper.insert(sysPlaintiffConfiguration);
        if (CollectionUtil.isNotEmpty(sysPlaintiffConfigurationRequest.getCourtIdList())) {
            for (String courtId : sysPlaintiffConfigurationRequest.getCourtIdList()) {
                sysPlaintiffConfigurationMapper.insertCourt(generateId, courtId);
            }
        }

        //文件上传
        PlaintiffFileRequest request = PlaintiffConfigurationConverter.INSTANCE.reqToFileReq(sysPlaintiffConfigurationRequest);
        request.setPlaintiffId(sysPlaintiffConfigurationRequest.getId());
        List<MultipartFile> businessLicenseFile = request.getBusinessLicenseFile();
        List<MultipartFile> idCardFile = request.getIdCardFile();
        List<MultipartFile> legalRepresentativeProveFile = request.getLegalRepresentativeProveFile();
        List<MultipartFile> sealFile = request.getSealFile();
        request.setFileType("business_license");
        uploadFile(businessLicenseFile, request);
        request.setFileType("id_card");
        uploadFile(idCardFile, request);
        request.setFileType("legal_person_identification");
        uploadFile(legalRepresentativeProveFile, request);
        request.setFileType("stamp_file");
        uploadFile(sealFile, request);
        return Result.ok();
    }

    private void uploadFile(List<MultipartFile> files, PlaintiffFileRequest request) {
        if (CollectionUtil.isEmpty(files)) {
            return;
        }
        String headUrl = environment.getProperty("file.evidence.url");
        String property = environment.getProperty("file.plaintiff.url");
        FileOutputStream fs = null;
        InputStream in = null;
        LocalDate now = LocalDate.now();
        int year = now.getYear();
        int month = now.getMonthValue();
        int day = now.getDayOfMonth();
        //文件目录相对路径
        Path path = Paths.get(property, String.valueOf(year), String.valueOf(month), String.valueOf(day));
        //文件完整路径
        Path parentPath = Paths.get(headUrl, path.toString());

        if (Files.notExists(parentPath)) {
            try {
                Files.createDirectory(parentPath);
            } catch (IOException e) {
                throw new BusinessException(e);
            }
        }
        for (MultipartFile multipartFile : files) {
            String generateId = snowFlake.generateId();
            String originalFilename = multipartFile.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            try {
                multipartFile.transferTo(new File(headUrl + File.separator + property + File.separator + generateId + suffix));
                PlaintiffFile plaintiffFile = PlaintiffConfigurationConverter.INSTANCE.reqToDoFile(request);
                plaintiffFile.setFileUrl(File.separator + path + File.separator + generateId + suffix);
                plaintiffFile.setFileOrginalName(originalFilename);
                plaintiffFile.setId(generateId);
                plaintiffFileMapper.insert(plaintiffFile);
            } catch (Exception e) {
                throw new BusinessException(Result.SYS_FAILD, "保存失败了...", e);
            } finally {
                IOUtil.close(in, fs);
            }
        }
    }

}
